#!/usr/bin/env python3
"""
工具系统集成
"""

import os
from typing import Dict, Any, Optional, List
from .core.manager import ToolManager

# 尝试加载.env文件
try:
    from dotenv import load_dotenv

    load_dotenv()
except ImportError:
    # 如果没有python-dotenv，手动设置环境变量
    os.environ.setdefault("AMAP_API_KEY", "0f8ac5a10c1a035f1cb293f067fbd007")
    os.environ.setdefault(
        "GOOGLE_API_KEY", "AQ.Ab8RN6KGRNypgaxZ0VZuL36NDwqTfgTzEn5vaHFvfE0KtSSRdA"
    )
    os.environ.setdefault("GOOGLE_SEARCH_ENGINE_ID", "a20c76280d05048cf")
    os.environ.setdefault(
        "GITHUB_TOKEN",
        "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",
    )
from .tools.amap_tools import AmapGeocodingTool, AmapWeatherTool, AmapPOITool
from .tools.search_tools import GoogleSearchTool, StackOverflowTool, GitHubSearchTool
from .tools.analysis_tools import LogParserTool, ErrorStatisticsTool, TimePatternTool

# 全局工具管理器实例
_tool_manager = None


def get_tool_manager() -> ToolManager:
    """获取工具管理器实例"""
    global _tool_manager
    if _tool_manager is None:
        _tool_manager = ToolManager()
        _initialize_tools()
    return _tool_manager


def _initialize_tools():
    """初始化所有工具"""
    manager = _tool_manager

    # 注册高德地图工具
    amap_api_key = os.getenv("AMAP_API_KEY", "")
    if amap_api_key:
        manager.register_tool(
            AmapGeocodingTool(amap_api_key),
            category="geography",
            tags=["地图", "地理编码", "坐标"],
            enabled=True,
        )
        manager.register_tool(
            AmapWeatherTool(amap_api_key),
            category="geography",
            tags=["天气", "气象"],
            enabled=True,
        )
        manager.register_tool(
            AmapPOITool(amap_api_key),
            category="geography",
            tags=["POI", "兴趣点", "周边"],
            enabled=True,
        )
    else:
        # 即使没有API密钥也注册工具，但会返回配置提示
        manager.register_tool(
            AmapGeocodingTool(""),
            category="geography",
            tags=["地图", "地理编码", "坐标"],
            enabled=True,
        )
        manager.register_tool(
            AmapWeatherTool(""),
            category="geography",
            tags=["天气", "气象"],
            enabled=True,
        )
        manager.register_tool(
            AmapPOITool(""),
            category="geography",
            tags=["POI", "兴趣点", "周边"],
            enabled=True,
        )

    # 注册搜索工具
    google_api_key = os.getenv("GOOGLE_API_KEY", "")
    google_search_engine_id = os.getenv("GOOGLE_SEARCH_ENGINE_ID", "")
    if google_api_key and google_search_engine_id:
        manager.register_tool(
            GoogleSearchTool(google_api_key, google_search_engine_id),
            category="search",
            tags=["搜索", "Google"],
            enabled=True,
        )

    # Stack Overflow工具（无需API密钥）
    manager.register_tool(
        StackOverflowTool(),
        category="search",
        tags=["搜索", "技术问答", "StackOverflow"],
        enabled=True,
    )

    # GitHub搜索工具
    github_token = os.getenv("GITHUB_TOKEN", "")
    if github_token:
        manager.register_tool(
            GitHubSearchTool(github_token),
            category="search",
            tags=["搜索", "代码", "GitHub"],
            enabled=True,
        )

    # 注册分析工具
    manager.register_tool(
        LogParserTool(),
        category="analysis",
        tags=["日志", "解析", "分析"],
        enabled=True,
    )
    manager.register_tool(
        ErrorStatisticsTool(),
        category="analysis",
        tags=["统计", "错误", "分析"],
        enabled=True,
    )
    manager.register_tool(
        TimePatternTool(),
        category="analysis",
        tags=["时间", "模式", "分析"],
        enabled=True,
    )


def process_with_tools(user_query: str, intent: str = None) -> Dict[str, Any]:
    """使用工具处理用户查询"""
    manager = get_tool_manager()
    return manager.process_user_query(user_query, intent)


def execute_tool(tool_name: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
    """执行单个工具"""
    manager = get_tool_manager()
    result = manager.execute_tool(tool_name, parameters)
    return result.to_dict()


def get_available_tools() -> List[str]:
    """获取可用工具列表"""
    manager = get_tool_manager()
    return manager.get_available_tools()


def get_tool_schema(tool_name: str) -> Optional[Dict[str, Any]]:
    """获取工具调用模式"""
    manager = get_tool_manager()
    return manager.get_tool_schema(tool_name)


def get_tools_for_intent(intent: str) -> List[str]:
    """根据意图获取推荐工具"""
    manager = get_tool_manager()
    return manager.get_tools_for_intent(intent)


def search_tools(keyword: str) -> List[str]:
    """搜索工具"""
    manager = get_tool_manager()
    return manager.search_tools(keyword)


def get_tool_stats() -> Dict[str, Any]:
    """获取工具统计信息"""
    manager = get_tool_manager()
    return manager.get_tool_stats()
